import React, { useEffect, useState } from 'react'
import { Modal, Skeleton, Tabs, message } from 'antd'
import { categoryList } from '@/services/category'
import TabPane from '@ant-design/pro-card/es/components/TabPane'
import ProForm, {
  ProFormGroup,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-form'
import Random from './Random'
import Fixed from './Fixed'
import { addTestList, TestListData, TestListMod } from '@/services/testList'

const Create = (props) => {

  const {
    isCreateModalVisible,
    setIsCreateModalVisible,
    actionRef,
    testListId,
    setTestListId
  } = props

  const options = [
    { label: '单选题', value: 'radio' },
    { label: '多选题', value: 'checkbox' },
    { label: '判断题', value: 'judge' },
    { label: '填空题', value: 'fill' },
    { label: '简答题', value: 'short' },
    { label: '字母题', value: 'subsystem' },
  ]


  const [activeKey, setActiveKey] = useState('1')
  const [tabStatus, setTabStatus] = useState(false)
  const [selectOrder, setSelectOrder] = useState(undefined)
  const [testValue, setTestValue] = useState(undefined)

  //定义Form实例 用来操作表单
  const [formObj] = ProForm.useForm()

  useEffect(async () => {
    if (testListId) {
      const res = await TestListData(testListId)
      setTestValue(res.data[0])
      setSelectOrder(options.filter(item =>  res.data[0].order.split(',').includes(item.value)))
      formObj.setFieldsValue({'order': res.data[0].order.split(',')})
      setTabStatus(true)
    }
  }, [testListId])

  /**
   * 关闭创建modal
   */
  const clearCreateModal = () => {
    setTestValue(undefined)
    setTabStatus(false)
    setActiveKey('1')
    if (testListId !== undefined) {
      actionRef.current.reload()
    }
    setTestListId(undefined)
    setIsCreateModalVisible(false)
    formObj.setFieldsValue(null)
  }

  /**
   * 试卷分类数据
   * @returns {Promise<*[]>}
   */
  const getTestCategory = async () => {
    const response = await categoryList({ 'category_group': 'paper' })
    let categoryArr = []
    response.map((item) => {
      categoryArr.push({ label: item.name, value: item.id })
    })
    return categoryArr
  }

  /**
   * 科目分类数据
   * @returns {Promise<*[]>}
   */
  const getSubject = async () => {
    const response = await categoryList({ 'category_group': 'subject' })
    let subject = []
    response.map((item) => {
      subject.push({ label: item.name, value: item.id })
    })
    return subject
  }

  /**
   * 创建试卷并且解锁后续操作
   * @param value
   * @constructor
   */
  const CreateTest = async (value) => {
    let type = ''
    setSelectOrder(options.filter(item =>  value.order.includes(item.value)))

    value.order = value.order.join(',')

    let response = ''

    if (testListId === undefined) {
      response = await addTestList(value)
      setTestListId(response.data.id)
      type = '添加'
    } else {
      response = await TestListMod(testListId, value)
      type = '修改'
    }

    message.success(`${type}成功`)
    setTabStatus(true)
    setActiveKey('2')
  }

  return (
    <Modal
      title="添加试卷"
      footer={null}
      centered={true}
      bodyStyle={{ width: '100%'}}
      width="90%"
      visible={isCreateModalVisible}
      onCancel={clearCreateModal}
      afterClose={clearCreateModal}
      destroyOnClose={true}
      forceRender={true}
    >
      <div className="card-container">
        <Tabs type="card" activeKey={activeKey} onTabClick={(key) => {
          setActiveKey(key)
        }}>
          <TabPane tab="试卷基本信息" key="1">
            {
              testValue === undefined && testListId !== undefined
                ?
                <Skeleton active/>
                :
                <ProForm
                  form={formObj}
                  initialValues={testValue}
                  name="control-ref"
                  style={{ width: '50%', margin: '0 auto' }}
                  submitter={{
                    // 配置按钮文本
                    searchConfig: {
                      resetText: '重置',
                      submitText: '下一步',
                    },
                  }}
                  onFinish={(values) => CreateTest(values)}
                >
                  <ProFormText
                    name="name"
                    label="试卷名称"
                    placeholder="请输入试卷名称"
                    width="lg"
                    rules={[{ required: true }]}/>
                  <ProFormSelect
                    width="lg"
                    name="paper_id"
                    label="试卷分类"
                    request={getTestCategory}
                    placeholder="请选择试卷分类"
                    rules={[{ required: true, message: '您必须选择试卷分类!' }]}
                  />
                  <ProFormSelect
                    width="lg"
                    name="subject_id"
                    label="科目分类"
                    request={getSubject}
                    placeholder="请选择科目分类"
                    rules={[{ required: true, message: '您必须选择科目分类!' }]}
                  />
                  <ProFormSelect
                    width="lg"
                    mode="multiple"
                    request={async () => options}
                    name="order"
                    label="选择试题并排序"
                    rules={[{ required: true, message: '您必须选择试题!' }]}
                  />
                  <ProFormRadio.Group
                    name="type"
                    label="试卷类型"
                    options={[
                      {
                        label: '正常试卷',
                        value: 1,
                      },
                      {
                        label: '练习试卷',
                        value: 2,
                      },
                      {
                        label: '闯关试卷',
                        value: 3,
                      },
                    ]}
                  />
                  <ProFormGroup>
                    <ProFormSelect
                      name="artificial"
                      label="是否需要人工阅卷"
                      rules={[{ required: true }]}
                      request={async () => [
                        { label: '不需要', value: 0 },
                        { label: '需要', value: 1 },
                      ]}
                    />
                    <ProFormRadio.Group
                      name="status"
                      label="试卷状态"
                      options={[
                        {
                          label: '发布',
                          value: 1,
                        },
                        {
                          label: '不发布',
                          value: 0,
                        },
                      ]}
                    />
                  </ProFormGroup>
                </ProForm>
            }

          </TabPane>
          <TabPane tab="选择随机试题" disabled={!tabStatus} key="2">
            <Random
              selectOrder={selectOrder}
              testListId={testListId}
              setTestListId={setTestListId}
              testValue={testValue}
            />
          </TabPane>
          <TabPane tab="选择固定试题" disabled={!tabStatus} key="3">
            <Fixed
              selectOrder={selectOrder}
              testListId={testListId}
              setTestListId={setTestListId}
              setIsCreateModalVisible={setIsCreateModalVisible}
              actionRef={actionRef}
              testValue={testValue}
            />
          </TabPane>
        </Tabs>
      </div>
    </Modal>
  )
}

export default Create
